package leetcode.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution438 {

    public static void main(String[] args) {

        String s =  "abab", p = "ab";
        System.out.println(new Solution438().findAnagrams(s,p));

    }

    public List<Integer> findAnagrams(String s, String p) {
        ArrayList<Integer> res = new ArrayList<>();
        //用键值对保存p的各字符个数
        int[] count = new int[26];
        for (int i = 0; i < p.length(); i++) {
            count[p.charAt(i)-'a']++;
        }
        //在s中查找，如果当前字符在p剩余的字符集里
        for (int i = 0; i <= s.length()-p.length(); i++) {
            int[] tempCount = count.clone();
            int j = i;
            for (; j < i+p.length(); j++) {
                //出现不符合了，无论是出现了p中没有的字符或者出现的字符数超过p
                if(tempCount[s.charAt(j)-'a']==0) break;
                else tempCount[s.charAt(j)-'a']--;
            }
            if(j == i+p.length()) res.add(i);
        }
        return Arrays.asList(res.toArray(new Integer[res.size()]));
    }


}
